package com.kern.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.kern.common.base.ResponseResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;

/**
 * Created by caoshi at 22:02 2021-09-14
 */
public class RpcUtil {

    private static Logger logger = LoggerFactory.getLogger(RpcUtil.class);

    /**
     * 调用远程服务
     * @param serverName
     * @param params
     * @return
     */
    public static ResponseResult callService(String serverName, Object... params) {
        ResponseResult result;
        JSONArray paramsArray = new JSONArray();
        if (params != null && params.length > 0) {
            paramsArray.addAll(Arrays.asList(params));
        }
        RestTemplate restTemplate = (RestTemplate) BeanUtil.getBean("restTemplate");
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        HttpEntity<String> httpEntity = new HttpEntity(paramsArray.toJSONString(), headers);
        result = restTemplate.postForObject("http://" + serverName, httpEntity, ResponseResult.class);

        logger.info("callService返回结果 === {}", result);
        if (result == null || result.getCode() != 0) {
            logger.error(JSON.toJSONString(result));
        }
        return result;
    }




}
